﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using WebSiteAdminTool.UI.MembershipService;
using WebSiteAdminTool.UI.Utils;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using WebSiteAdminTool.UI.Utils.Commands;
using GalaSoft.MvvmLight.Messaging;
using WebSiteAdminTool.UI.ViewModels.Base;
using WebSiteAdminTool.UI.RolesService;

namespace WebSiteAdminTool.UI.ViewModels.Security.Roles
{
    public class ManageRoleViewModel : BaseDialogViewModel
    {
        #region private data

        private RoleData _role = null;
        
        #endregion

        #region public props

        public RoleData Role
        {
            get { return _role; }
            set { _role = value; }
        }

        //public string RoleName
        //{
        //    get { return _role.RoleName; }
        //    set
        //    {
        //        if (string.IsNullOrEmpty(value))
        //            throw new Exception("Please set a value");

        //        _role.RoleName = value;
        //    }
        //}

        //public string Comment
        //{
        //    get { return _role.Comment; }
        //    set { _role.Comment = value; }
        //}

        public override string DialogTitle
        {
            get { return Mode == DialogMode.New ? "Create Role" : "Manage Role"; }
        }

        #endregion

        #region data methods

        protected override void DoSave()
        {
            if (null != this.Role)
            {
                var client = new RolesServiceClient();
                if (Mode == DialogMode.New)
                {
                    CreateRole(client);
                }
                else
                {
                    UpdateRole(client);
                }
            }
        }

        private void CreateRole(RolesServiceClient client)
        {
            client.CreateRoleCompleted += new EventHandler<CreateRoleCompletedEventArgs>(client_CreateRoleCompleted);
            client.CreateRoleAsync(this.Role);
        }

        private void UpdateRole(RolesServiceClient client)
        {
            client.UpdateRoleCompleted += new EventHandler<UpdateRoleCompletedEventArgs>(client_UpdateRoleCompleted);
            client.UpdateRoleAsync(this.Role);
        }

        void client_CreateRoleCompleted(object sender, CreateRoleCompletedEventArgs e)
        {
            SaveCompleted<RoleData>(e, e.Result);
        }

        void client_UpdateRoleCompleted(object sender, UpdateRoleCompletedEventArgs e)
        {
            SaveCompleted<RoleData>(e, e.Result);
        }

        #endregion
    }
}
